<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Models\system\NewsMiddleModel;
use App\Models\system\NewsModel;
use Illuminate\Http\Request;
use lxs\api\ApiResponse;

class NewsController extends Controller
{

    /**
     * 获取新闻列表
     */
    public function getNewsList(Request $request): \Illuminate\Http\JsonResponse
    {
        $uid = $request->uid;
        $page = $request->input('page');
        $pageSize = $request->input('page_size');

        $model = NewsModel::select('news.*', 'news_middle.is_browse', 'news_middle.is_delete')
            ->rightJoin('news_middle', function ($join) use ($uid) {
                $join->on('news.id', '=', 'news_middle.news_id')
                    ->where('news_middle.uid', '=', $uid)
                    ->where('news_middle.is_delete', '=', 0);
            })
            ->where('news.is_deleted', 0);

        $count = $model->count();

        $list = $model->orderBy('is_new', 'desc')
                ->orderBy('sort', 'desc')
                ->orderBy('update_time', 'desc')
                ->offset(($page - 1) * $pageSize)
                ->limit($pageSize)
                ->get()->toArray();

        return ApiResponse::success('获取新闻列表成功', ['list' => $list, 'total' => $count]);
    }


    /**
     * 删除新闻列表
     */
    public function deleteNews(Request $request) {
        $id = $request->input('id');
        $uid = $request->uid;
        $list = NewsMiddleModel::where('news_id', 1)->where('uid', 1)->first();
        if ($list) {
            $list->is_delete = 1;
            $list->save();
            return ApiResponse::success('删除成功');
        }
        return ApiResponse::error('删除失败');
    }


    /**
     * 获取新闻详情
     */
    public function getNewsDetail(Request $request) {
        $news_id = $request->input('news_id');
        $list = NewsModel::where('id', $news_id)->first();
        if ($list) {
            return ApiResponse::apiResponseData(200, '获取新闻详情成功', [
                'list' => $list,
            ]);
        }
        return ApiResponse::error('获取新闻详情失败');
    }

}
